package com.salary.utils.reader;

import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 读个税数据表
 */
public class TaxDataReader extends DataReader<Map<String,Double>>{
    private static final Logger logger = LoggerFactory.getLogger(SalesDataReader.class);
    /**
     * 从个税表读取个税数据
     *
     * @param taxFilePath 个税表文件路径
     * @return 姓名到个税金额的映射
     */
    @Override
    public Map<String, Double> readData(String taxFilePath) {
        Map<String, Double> taxData = new HashMap<>();

        try (FileInputStream fis = new FileInputStream(taxFilePath);
             Workbook workbook = WorkbookFactory.create(fis)) {

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                logger.error("个税表中未找到工作表");
                return taxData;
            }

            logger.info("从个税表的'" + sheet.getSheetName() + "'工作表读取数据");

            // 查找姓名列和个税列的索引
            int nameColIndex = -1;
            int taxColIndex = -1;

            // 检查前三行可能的表头
            for (int rowIdx = 0; rowIdx <= 2; rowIdx++) {
                Row headerRow = sheet.getRow(rowIdx);
                if (headerRow == null) continue;

                for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                    Cell cell = headerRow.getCell(i);
                    if (cell == null) continue;

                    String cellValue = getCellValueAsString(cell).trim();
                    if (cellValue.contains("姓名") || cellValue.equals("姓名") || cellValue.equals("名字") || cellValue.equals("名称")) {
                        nameColIndex = i;
                        logger.info("找到姓名列，在第" + (rowIdx+1) + "行，索引: " + nameColIndex);
                    } else if (cellValue.contains("个税") || cellValue.equals("个税") || cellValue.contains("个人所得税") || cellValue.contains("税") || cellValue.contains("税款")) {
                        taxColIndex = i;
                        logger.info("找到个税列，在第" + (rowIdx+1) + "行，索引: " + taxColIndex);
                    }
                }

                // 如果在当前行找到了需要的列，就不再继续查找
                if (nameColIndex != -1 && taxColIndex != -1) {
                    break;
                }
            }

            if (nameColIndex == -1 || taxColIndex == -1) {
                logger.error("个税表中未找到必要的列");
                return taxData;
            }

            // 查找第一个非表头数据行的开始
            int startRowIndex = -1;
            for (int i = 0; i <= 5; i++) {  // 检查前6行
                Row row = sheet.getRow(i);
                if (row != null) {
                    Cell nameCell = row.getCell(nameColIndex);
                    if (nameCell != null) {
                        String name = getCellValueAsString(nameCell).trim();
                        // 如果不是空白，且不是列标题，就认为是数据行的开始
                        if (!name.isEmpty() && !name.contains("姓名")) {
                            startRowIndex = i;
                            break;
                        }
                    }
                }
            }

            if (startRowIndex == -1) {
                startRowIndex = 1;  // 默认从第二行开始
            }

            // 从数据行开始读取数据
            for (int rowIndex = startRowIndex; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row == null) continue;

                Cell nameCell = row.getCell(nameColIndex);
                if (nameCell == null) continue;

                String name = getCellValueAsString(nameCell).trim();
                if (name.isEmpty() || name.contains("姓名") || name.equals("姓名")) continue;

                Cell taxCell = row.getCell(taxColIndex);
                if (taxCell == null) continue;

                double tax = getCellValueAsDouble(taxCell);

                // 如果税额为0，则尝试直接读取单元格的字符串值并转换
                if (tax == 0) {
                    try {
                        String taxStr = getCellValueAsString(taxCell).trim();
                        if (!taxStr.isEmpty()) {
                            // 移除可能的货币符号和千分位分隔符
                            taxStr = taxStr.replace(",", "").replace("¥", "").replace("￥", "");
                            tax = Double.parseDouble(taxStr);
                        }
                    } catch (NumberFormatException e) {
                        // 忽略解析错误
                    }
                }

                // 只有当税额不为0时才添加记录
                if (tax != 0) {
                    taxData.put(name, tax);
                    logger.info("读取到个税数据: " + name + " - " + tax);
                }
            }

            logger.info("成功从个税表读取了 " + taxData.size() + " 条记录");

        } catch (IOException e) {
            logger.error("读取个税表文件失败: " + e.getMessage(), e);
        }

        return taxData;
    }

}
